package com.github.aloxc.plugin.restplus.i18n;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
/**
 *
 * @author leero
 */
public class XmlControl
        extends ResourceBundle.Control
{
    @Override
    public List<String> getFormats(String baseName) {
        if (baseName == null) {
            throw new NullPointerException();
        }
        return Collections.singletonList("xml");
    }



    @Override
    public Locale getFallbackLocale(String baseName, Locale locale) { return null; }

    @Override
    public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException {
        if (baseName == null || locale == null || format == null || loader == null){
            throw new NullPointerException();
        }
        Object object = null;
        if ("xml".equals(format)) {
            InputStream stream;
            String bundleName = toBundleName(baseName, locale);
            String resourceName = toResourceName(bundleName, format);
            if (reload) {
                stream = getInputStream(loader, resourceName);
            } else {
                stream = loader.getResourceAsStream(resourceName);
            }
            if (stream != null) {
                BufferedInputStream bis = new BufferedInputStream(stream);
                object = new XmlResourceBundle(bis);
                bis.close();
            }
        }
        return (ResourceBundle)object;
    }


    private InputStream getInputStream(ClassLoader loader, String resourceName) throws IOException {
        URL url = loader.getResource(resourceName);
        if (url == null) {
            return null;
        }
        URLConnection connection = url.openConnection();
        if (connection == null) {
            return null;
        }
        connection.setUseCaches(false);
        return connection.getInputStream();
    }
}